package manager.pay;

import manager.connection.ClientConnectionManager;
import manager.http.HttpClient;
import manager.pay.type.GetMidTradePackageInfo;
import net.socket.server.SocketServer;
import net.socket.server.protocal.PROTOID;
import net.socket.server.request.IRequest;
import net.socket.server.response.MidTradrPackageResponse;
import observable.subject.MessageCenter;
import util.MyFactory;
import util.ResultTypeList;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.utils.URIBuilder;
import org.springframework.beans.BeansException;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;


import io.netty.channel.ChannelFuture;

/**
 * 类名：GetMidTradePackage
 * 描述：获取机器的套餐
 * @author zk
 * @date 2018-4-24
 * @version 0.0.1
 * 
 *
 */
public class GetMidTradePackage {
	private ClientConnectionManager ccm = null;
	//这个hashmap主要是为了防止平台崩溃,client获取不了套餐消息,所以长度为4
	private  static Map<Integer, GetMidTradePackageInfo> MidPackageMap = new HashMap<Integer,GetMidTradePackageInfo>();
	
	public void init(){
		MessageCenter messageCenter = MyFactory.context.getBean("MessageCenter", MessageCenter.class);
		messageCenter.register(PROTOID.REQ_MID_TRADR_PACKAGE, (int cmd, IRequest req)->handMidTradrPackage(cmd, req));
		
		ccm = MyFactory.context.getBean("ClientConnectionManager", ClientConnectionManager.class);
	}
	
	private int handMidTradrPackage(int cmd, IRequest req) throws URISyntaxException, IllegalArgumentException, IllegalAccessException, BeansException, ParseException, IOException {
		MidTradrPackageResponse rsp = new MidTradrPackageResponse();
		//URI getUri = new URIBuilder("http://14.119.109.232:30666/center/manager/?")
		URI getUri = new URIBuilder("http://"+SocketServer.adress+":30666/center/manager/?")
				.addParameter("cmd", "query_machine_tradepackage")
        		.addParameter("mid", Integer.toString(req.getMachineId()))
        		.build();
		String httpResult;
		httpResult = MyFactory.context.getBean("HttpClient", HttpClient.class).httpGet(getUri);
		if(httpResult ==null) {
			rsp = handleExcption();
			ccm.sendResponse(PROTOID.RSP_MID_TRADR_PACKAGE, req.getMachineId(), rsp);
			return ResultTypeList.SUCCESS;
		}
		rsp = ToMidTradrPackageResponse(httpResult);

		ccm.sendResponse(PROTOID.RSP_MID_TRADR_PACKAGE, req.getMachineId(), rsp);
	
		return ResultTypeList.SUCCESS;
	}
	private MidTradrPackageResponse handleExcption() {
		MidTradrPackageResponse rsp = new MidTradrPackageResponse();
		ArrayList<GetMidTradePackageInfo> tradrPackageInfo = new ArrayList<GetMidTradePackageInfo>();
		if(MidPackageMap.isEmpty()) {
			return rsp;
		}
		int num =0;
		for(Integer key: MidPackageMap.keySet()) {
			if(num ==3) 
				break;
			tradrPackageInfo.add(MidPackageMap.get(key));
			num++;
		}
		rsp.setTradrPackageInfo(tradrPackageInfo);;
		return rsp;
	}

	/**
	 * @description 将php后台返回来的机器套餐信息翻译成MidTradrPackageResponse
	 * @param httpResult
	 * @return
	 */
	private MidTradrPackageResponse ToMidTradrPackageResponse(String httpResult) {
		
		MidTradrPackageResponse rsp = new MidTradrPackageResponse();
		ArrayList<GetMidTradePackageInfo> tradrPackageInfo = new ArrayList<GetMidTradePackageInfo>();
		GetMidTradePackageInfo gInfo = null;
		JsonObject jsonResult = null;
        JsonParser parse =new JsonParser();
      
        jsonResult = (JsonObject) parse.parse(httpResult);//解析成json
        JsonArray jsonArray = jsonResult.get("result").getAsJsonArray();//转换成json数组
        int jsonSize = jsonArray.size();
        for(int i=0;i<jsonSize;i++) {
        	jsonResult = (JsonObject) jsonArray.get(i);
        	gInfo =new GetMidTradePackageInfo();
        	gInfo.setPacketId(Integer.parseInt(jsonResult.get("tradeid").toString()));
        	gInfo.setTradeName(jsonResult.get("tradename").toString());   
        	gInfo.setPrice(Double.parseDouble(jsonResult.get("price").toString()));
        	int kCoin=(int)Math.pow(gInfo.getPrice()*10, 1);//10k币一块钱
        	gInfo.setkCoin(kCoin);
        	tradrPackageInfo.add(gInfo);
        	//System.out.println("tradeid:"+gInfo.getPacketId());
        	//if(null==MidPackageMap.get(gInfo.getPacketId())&&MidPackageMap.size()<4) 
         	MidPackageMap.put(gInfo.getPacketId(), gInfo);
        	
        }
        rsp.setTradrPackageInfo(tradrPackageInfo);
       
      
		return rsp;
	}
	
	public GetMidTradePackageInfo getMidPackage(int packetId) {
		return MidPackageMap.get(packetId);
		
	}

}
